import { useState, useEffect, useRef } from 'react';
import { Button, message } from 'antd';
import CommonTable from '@/components/CommonTable';
import FooterToolbar from '@/components/FooterToolbar';
import CommonPagination from '@/components/CommonPagination';
import CommonLoading from '@/components/CommonLoading';
import DetailModal from './DetailModal';
import moment from 'moment';
import { handleExportExcel } from '@/utils/utils.jsx';
import { stringify } from 'qs';
import { queryPageList } from '../service';

const initPagination = {
  current: 1,
  total: 0,
  pageSize: 20,
  showQuickJumper: true,
  pageSizeOptions: [10, 20, 50, 500],
};

const dateFormat = 'YYYY-MM-DD HH:mm:ss';

const TableContent = ({ query, divEl, tableKey }) => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [pagination, setPagination] = useState({ ...initPagination }); //分页数据
  const [item, setItem] = useState({}); //单行的数据

  const [visible, setVisible] = useState(false); 

  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  useEffect(() => {
    if (tableKey) {
      getTableListFunc(query, {
        ...pagination,
        current: 1,
      });
    }
  }, [tableKey]);

  //获取列表数据
  const getTableListFunc = async (query, pagination) => {
    setLoading(true);
    const params = {
      ...query,
      size: pagination.pageSize,
      current: pagination.current,
    };
    if (params.time) {
      params.startTime = moment(params.time[0]._d).format(dateFormat);
      params.endTime = moment(params.time[1]._d).format(dateFormat);
    }
    params.time = undefined;
    setData([]);
    const { data, success } = await queryPageList(params);
    if (success) {
      const { records = [], total = 0 } = data || {};
      pagination.total = total;
      setData(records);
    } else {
      pagination.total = 0;
      setData([]);
    }
    setPagination(pagination);
    setLoading(false);
  };

  const columns = [
    {
      title: '销退入库单号',
      dataIndex: 'returnOrderSn',
      key: 'returnOrderSn',
      width: 100,
    },
    {
      title: '退货物流单号',
      dataIndex: 'logisticsNo',
      key: 'logisticsNo',
      width: 100,
    },
    {
      title: '系统订单号',
      dataIndex: 'orderSn',
      key: 'orderSn',
      width: 100,
    },
    {
      title: '总销退数量（正品、次品）',
      dataIndex: 'goodsName',
      key: 'goodsName',
      width: 90,
      render: (text, record, index) => (
        <span>
          <span>
            {record?.qualityNum}、 {record?.defectiveNum}
          </span>
        </span>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 100,
    },
    {
      title: '操作人',
      dataIndex: 'createAccount',
      key: 'createAccount',
      width: 100,
    },
    {
      title: '操作',
      width: '15%',
      key: 'opera',
      render: (text, record, index) => (
        <span className="opera-span-common">
          <span onClick={() => getDetail(record)}>查看商品详情</span>
        </span>
      ),
    },
  ];

  //获取详情
  const getDetail = (record) => {
    setVisible(true);
    setItem(record);
  };

  //表格滚动高度
  const [scrollHeight, setScrollHeight] = useState(580);

  //监听窗口尺寸变化计算一下高度
  useEffect(() => {
    window.addEventListener('resize', () => {
      handleSetHeight();
    });
    return () => {
      window.removeEventListener('resize', () => {
        handleSetHeight();
      });
    };
  }, []);

  //计算表格的滚动高度
  const handleSetHeight = () => {
    try {
      const sumHeight = document.getElementById('sectionContent').clientHeight;
      const searchHeight =
        divEl && divEl.current ? divEl.current.clientHeight : 0;
      const finalHeight = sumHeight - (searchHeight + 128);
      setScrollHeight(finalHeight);
    } catch (e) {
      console.log(e);
    }
  };

  //表格
  const tableProps = {
    data,
    columns,
    rowKey: 'id',
    scroll: { y: scrollHeight },
    // rowSelection: {
    //   columnWidth: 45,
    //   type: 'checkbox',
    //   //   fixed: true,
    //   selectedRowKeys,
    //   onChange: (selectedRowKeys) => {
    //     setSelectedRowKeys(selectedRowKeys);
    //   },
    // },
  };

  //导出功能
  const exportExcel = () => {
    const { total } = pagination;
    if (total) {
      const nums = Math.ceil(total / 10000);
      message.info(`即将为您导出${nums}张Excel，请稍候...`);

      setLoading(true);
      const params = {
        ...query,
        size: pagination.pageSize,
        current: pagination.current,
      };
      if (params.time) {
        params.startTime = moment(params.time[0]._d).format(dateFormat);
        params.endTime = moment(params.time[1]._d).format(dateFormat);
      }
      params.time = undefined;
      params.current = 1;
      params.size = 10000;
      const handleExport = () => {
        handleExportExcel(
          `/zjf-wms/refundStorage/export?${stringify(params)}`,
          '销退入库单.xlsx',
          commonCallback
        );
      };
      const commonCallback = () => {
        params.current++;
        if (params.current <= nums) {
          message.info(`总计${nums}张，即将为您导出第${params.current}张`);
          handleExport();
        }
        setLoading(false);
      };
      handleExport();
    } else {
      message.info('暂无可导出的数据！');
    }
  };

  //详情弹窗
  const GoodsDetailProps = {
    visible,
    item,
    handleVisible() {
      setVisible(false);
    },
  };

  //分页
  const pageProps = {
    pagination,
    handleChange(current, size) {
      setPagination({
        ...pagination,
        current: current,
        pageSize: size,
      });
      getTableListFunc(query, { ...pagination, current, pageSize: size });
    },
  };

  return (
    <>
      <div className="common-table-header-btn">
        <Button
          shape="round"
          className="newRoundBtn"
          onClick={() => exportExcel()}
          style={{ marginRight: 6 }}
        >
          导出表格
        </Button>
      </div>
      <CommonTable {...tableProps} />
      {visible && <DetailModal {...GoodsDetailProps} />}
      <FooterToolbar>
        <CommonPagination {...pageProps} />
      </FooterToolbar>
      <CommonLoading loading={loading} />
    </>
  );
};

export default TableContent;
